﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;

namespace Pibby.Core.Plugins
{
	public class PluginCollection : Collection<IPlugin>
	{
		public PluginCollection ()
		{
			this.ScanForPlugins();
		}

		private void ScanForPlugins()
		{
			Type interfaceType = typeof(IPlugin);

			// just using current domain because 
			// only assemblies here should be our own or plugins.

			var plugins = AppDomain
				.CurrentDomain
				.GetAssemblies()
				.SelectMany(assembly => assembly.GetTypes())
				.Where(type => interfaceType.IsAssignableFrom(type)
								&& !type.IsAbstract
								&& !type.IsInterface
								&& type.GetConstructors().Length > 0);

			foreach (Type plugin in plugins)
			{
				IPlugin pluginInstance = Activator.CreateInstance(plugin) as IPlugin;

				if (pluginInstance != null)
					this.Add(pluginInstance);
			}
		}
	}
}
